import React, { createContext, useState, useReducer, useEffect } from 'react';
import { createReducerMapper, useMyReducer } from '@/utils/index';
import { Product_Web } from '@/pages/_server/_class/Product/Product';
import { Activities_Web } from '@/pages/_server/_class/MyActivities/ActivitiesList';
import { apiGetActivitesList } from '@/pages/_server/_api/ApiActivities/apiGetActivitesList';
export type ActivitiesContextType = {
    activitiesExhibitionState: ActivitiesExhibition;
};

export const ActivitiesContext = createContext<ActivitiesContextType>(undefined);

/** 页面渲染的列表 */
export type ActivitiesExhibition = {
    // productList: Product_Web[];
    // gotoPageDetail: (productId: string) => void;
    bannerList: Product_Web[];
    activitiesList: Activities_Web[];
};

/** 处理reducer的函数 */
const handleMapper = createReducerMapper({
    initializer: null as ActivitiesExhibition,
    handleMapper: {
        /** 刷新列表 */
        freshList: (state, payload?: { productList: Activities_Web[] }) => {
            let list = [...payload.productList];
            let newState: Pick<ActivitiesExhibition, 'activitiesList'> = {
                activitiesList: [],
            };
            newState.activitiesList = [...list];
            return { ...state, ...newState };
        },
    },
});

const initialState: ActivitiesExhibition = {
    bannerList: [],
    activitiesList: [],
};

/** 使用需要展示的列表 */
export const useActivitiesExhibitionList = () => {
    const [activitiesExhibitionState, activitiesExhibitionDispatch] = useMyReducer({
        initializer: initialState,
        handleMapper,
    });
    useEffect(() => {
        // 页面加载完成时初始化列表
        apiGetActivitesList().then((res) => {
            if (!res) return;
            activitiesExhibitionDispatch({
                type: 'freshList',
                payload: {
                    productList: res.data,
                },
            });
        });
    }, [activitiesExhibitionDispatch]);

    return {
        activitiesExhibitionState,
    };
};
